package sisdroid.client;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import sisdroid.client.model.Location;

import android.app.Activity;
import android.content.Context;
import android.telephony.CellLocation;
import android.telephony.NeighboringCellInfo;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.telephony.cdma.CdmaCellLocation;
import android.telephony.gsm.GsmCellLocation;
import android.test.IsolatedContext;
/**
 * CellIdDiscoverer.
 *
 * Returns the current attached GSM cell.
 * 
 * @author mwn
 *
 */
public class CellIdDiscoverer implements NetDiscoverer
{
	GsmCellLocation currentCell;
	TelephonyManager manager;
	public CellIdDiscoverer( Activity activity )
	{
		manager = (TelephonyManager) activity.getSystemService( Context.TELEPHONY_SERVICE ); 
		
		CellLocation loc = manager.getCellLocation();
		if ( loc != null && loc instanceof GsmCellLocation )
			currentCell = (GsmCellLocation) loc;
		else
			currentCell = null;
		
		PhoneStateListener psl = new PhoneStateListener()
		{
			public void onCellLocationChanged(CellLocation location)
			{
				if ( location instanceof GsmCellLocation )
				{
					if ( currentCell != null )
						currentCell = (GsmCellLocation) location;
				}
				else if ( location instanceof CdmaCellLocation )
				{
					currentCell.setLacAndCid( -123, -123 );
				}
			};
		};
		
		manager.listen( psl, PhoneStateListener.LISTEN_CELL_LOCATION );
	}

	@Override
	public Set<sisdroid.client.model.Location> getNetIDS()
	{

		Set<sisdroid.client.model.Location> result = new HashSet<sisdroid.client.model.Location>();
		
		List<NeighboringCellInfo> scanresult =  manager.getNeighboringCellInfo();

		CellLocation.requestLocationUpdate();
		
		if ( currentCell != null )
		{
			result.add( new Location( "CellGSM" , currentCell.getCid() + "/" + currentCell.getLac() ) );
		}
		
		if ( scanresult != null )
		{
			// TODO: Should we really have signal strength in the identification?
			for ( NeighboringCellInfo nci : scanresult )
			{
				switch ( nci.getNetworkType() )
				{
					case TelephonyManager.NETWORK_TYPE_EDGE:
					case TelephonyManager.NETWORK_TYPE_GPRS:
						result.add( new sisdroid.client.model.Location("CellGSM" , nci.getCid() + "/" + nci.getLac() + "/" + nci.getRssi()) );
						break;
					case TelephonyManager.NETWORK_TYPE_UMTS:
					case TelephonyManager.NETWORK_TYPE_HSDPA:
					case TelephonyManager.NETWORK_TYPE_HSUPA:
					case TelephonyManager.NETWORK_TYPE_HSPA:
						result.add( new sisdroid.client.model.Location( "CellUMTS", "" + nci.getPsc() ) );
						break;
					case TelephonyManager.NETWORK_TYPE_UNKNOWN:
						break;
					default:
						break;
				}	
			}
		}
		
		return result;
	}

}
